# -*- coding: utf-8 -*-
import uuid
from datetime import datetime
import os

import oss2
# from oss2.credentials import EnvironmentVariableCredentialsProvider
from config import OSS_ACCESS_KEY_SECRET,OSS_ACCESS_KEY_ID,endpoint,bucketName,region


class Aliyun:
    # 加载凭证
    # 方式一：
    # 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    #auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())  # 使用 ProviderAuth 而不是 ProviderAuthV4
    # 方式二：
    auth = oss2.Auth(OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET)

    # 创建Bucket实例，指定存储空间的名称和Region信息。
    bucket = oss2.Bucket(auth, endpoint, bucketName)

    @classmethod
    def upload_avatar(cls, avatar_path):
        """
        上传文件到OSS。
        :param avatar_name: 上传到OSS后的文件名
        :param avatar_path: 本地文件路径
        """
        print(avatar_path)
        avatar_name = os.path.basename(avatar_path)
        dir = datetime.now().strftime("%Y/%m")
        new_file_name = str(uuid.uuid4()) + avatar_path[avatar_path.rindex('.'):]
        objectName = dir + "/" + new_file_name
        try:
            cls.bucket.put_object_from_file(objectName, avatar_path)
            print(f"文件 {avatar_name} 上传成功")
            return "https://" + bucketName + "." + endpoint + "/" + objectName
        except oss2.exceptions.OssError as e:
            raise Exception(f"文件上传失败: {e}")